import React from 'react';
import {Menu, Icon, Button, message} from 'antd';
import * as FileSaver from 'file-saver';
import './index.css';
import {axiosPostFunction} from "../MyConfig/AppConfig";
const ButtonGroup = Button.Group;
const {SubMenu} = Menu;

// 下面这个是 Header 组件，代表上方导航栏
const Header = ({canvas, history}) => {

    // 从 json 文件中引入
    const onHandleImportJson = () => {
        const input = document.createElement('input');
        input.type = 'file';
        input.onchange = event => {
            const elem = event.srcElement || event.target;
            if (elem.files && elem.files[0]) {
                const reader = new FileReader();
                reader.onload = e => {
                    const text = e.target.result + '';
                    try {
                        const data = JSON.parse(text);
                        console.log("Header: onHandleImportJson: canvas.open(data): data: ", data)
                        canvas.open(data);
                    } catch (e) {
                        return false;
                    }
                };
                reader.readAsText(elem.files[0]);
            }
        };
        input.click();
    }

    // 保存为 svg
    const onHandleSaveToSvg = () => {
        const C2S = window.C2S;
        const ctx = new C2S(canvas.canvas.width + 200, canvas.canvas.height + 200);
        if (canvas.data.pens) {
            for (const item of canvas.data.pens) {
                item.render(ctx);
            }
        }
        let mySerializedSVG = ctx.getSerializedSvg();
        mySerializedSVG = mySerializedSVG.replace('<defs/>',
            `<defs><style type="text/css">@font-face {font-family: 'topology';src: url('http://at.alicdn.com/t/font_1331132_h688rvffmbc.ttf?t=1569311680797') format('truetype');}</style></defs>`
        );
        mySerializedSVG = mySerializedSVG.replace(/--le5le--/g, '&#x');
        const urlObject = window.URL || window;
        const export_blob = new Blob([mySerializedSVG]);
        const url = urlObject.createObjectURL(export_blob);
        const a = document.createElement('a');
        a.setAttribute('download', 'le5le.topology.svg');
        a.setAttribute('href', url);
        const evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, true);
        a.dispatchEvent(evt);
    }

    // 点击导航栏后根据 key 进行解析的函数
    const onHandleSelect = data => {
        switch (data.key) {
            case 'create_new':
                canvas.open({nodes: [], lines: []});
                break;
            case 'import_json':
                onHandleImportJson();
                break;
            case 'save_json':
                FileSaver.saveAs(
                    new Blob([JSON.stringify(canvas.data)], {type: 'text/plain;charset=utf-8'}),
                    `le5le.topology.json`
                );
                break;
            case 'save_png':
                canvas.saveAsImage('le5le.topology.png');
                break;
            case 'save_svg':
                onHandleSaveToSvg();
                break;
            case 'undo':
                canvas.undo();
                break;
            case 'redo':
                canvas.redo();
                break;
            case 'copy':
                canvas.copy();
                break;
            case 'cut':
                canvas.cut();
                break;
            case 'paste':
                canvas.paste();
                break;
            case 'preview':
                let reader = new FileReader();
                console.log(canvas.data);
                const result = new Blob([JSON.stringify(canvas.data)], {type: 'text/plain;charset=utf-8'});
                reader.readAsText(result, 'text/plain;charset=utf-8');
                reader.onload = (e) => {
                    history.push({pathname: '/preview', state: {data: JSON.parse(reader.result)}});
                }
                break;
            default:
                break;
        }
    }

    // 点击发布之后的函数
    const onClickPublish = () => {
        // message.success("Published！");
        let canvasData = JSON.stringify(canvas.data);
        console.log(canvasData);
        axiosPostFunction(
            "/file/publish",
            {
                userId: 1,
                content: canvasData
            },
            (resData)=>{
                message.success("发送成功！")
                console.log(resData);
            }
        )
    }

    // 返回和渲染值
    return (
        <div style={{height: 48, width: '100vw', borderBottom: '1px solid #e8e8e8'}}>
            {/* 左上角菜单栏 */}
            <Menu mode="horizontal" style={{width: 500, float: 'left'}} onClick={onHandleSelect}>
                <Menu.Item disabled={true} style={{marginBottom: -10, marginLeft: 10}}><h2>组态管理系统</h2></Menu.Item>
                <SubMenu
                    title={
                        <span className="submenu-title-wrapper"><Icon type="file"/>文件</span>
                    }
                >
                    <Menu.Item key="create_new">新建文件</Menu.Item>
                    <Menu.Item key="import_json">打开本地文件</Menu.Item>
                    <Menu.Divider/>
                    <Menu.Item key="save_json">保存到本地</Menu.Item>
                    <Menu.Item key="save_png">保存为PNG</Menu.Item>
                    <Menu.Item key="save_svg">保存为SVG</Menu.Item>
                </SubMenu>
                <SubMenu
                    title={<span className="submenu-title-wrapper"><Icon type="appstore"/>系统</span>}
                >
                    <Menu.Item key="component_management">组态管理</Menu.Item>
                    <Menu.Item key="person_center">个人中心</Menu.Item>
                    <Menu.Item key="my_file">我的作品</Menu.Item>
                </SubMenu>
            </Menu>
            <ButtonGroup style={{float: 'right', right: 10, marginTop: 7}}>
                <Button onClick={() => onHandleSelect({key: 'preview'})}>
                    <Icon type="eye"/>预览
                </Button>
                {/* 20211102 新增一个发布的按钮 */}
                <Button onClick={() => onClickPublish()}>
                    <Icon type="share-alt" />
                    发布
                </Button>
            </ButtonGroup>
        </div>
    );
};

export default Header;
